package com.topisv.tms.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.SubWarehouseRel;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.WarehouseArea;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.SubWarehouseRelService;
import com.topisv.tms.service.WarehouseAreaService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 服务网点管理的Controller, 使用Restful风格的Urls:
 * 
 * List page     : GET /areaGroup/
 * Create page   : GET /areaGroup/create
 * Create action : POST /areaGroup/create
 * Update page   : GET /areaGroup/update/{id}
 * Update action : POST /areaGroup/update
 * Delete action : GET /areaGroup/delete/{id}
 * 
 * @author Arthur
 */
/**
 * 
 * @author <a href=mailto:libin@nryuncang.com>libin</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping(value = "/areaGroup")
public class AreaGroupController extends BaseDataTableController{
    
	private static final Logger log = LoggerFactory.getLogger(AreaGroupController.class);

	private static final int PAGE_SIZE = 10;

	@Autowired
	private AreaGroupService areaGroupService;
	
	@Autowired
	private AreaService areaService;
	@Autowired
	private WarehouseAreaService warehouseAreaService;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "sortType", defaultValue = "groupName_asc") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Page<AreaGroup> areaGroups = areaGroupService.getAreaGroup(searchParams, pageNumber, PAGE_SIZE, sortType);
		List<AreaGroup> areaGroupsList = areaGroups.getContent();
		
		for(int i=0; i<areaGroupsList.size(); i++){
			AreaGroup ag = areaGroupsList.get(i);
			if(0 != ag.getAreas().length()){
				String[] areaCodes = ag.getAreas().split(";");
				ArrayList<String> temp = new ArrayList<String>();
				for(int j=0; j<areaCodes.length; j++) {
					temp.add(areaService.getAreaByCode(areaCodes[j]).getAreaName() + ";");
				}
				ag.setProvinces(temp.toArray(areaCodes));
			}
		}
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("sortType", sortType);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

		return "areagroup/areaGroupList";
	}
	
	@RequestMapping(value = "detailArea", method = RequestMethod.POST)
	public String detailArea(@RequestParam(value = "id", required = false) Long id, HttpServletResponse response) {
		List<Area> areas = areaGroupService.getAreaByAreaGroupId(id);
		Map<String,List<Area>> map = new HashMap<String,List<Area>>();
		map.put("areas", areas);
		String json = JsonUtil.getObjectString(areas);
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(json);
		} catch (IOException e) {
			
		}
		return null;
	}
	

	
	@RequestMapping(value = "areaGroupDetail")
	public void AreaGroupDetail(HttpServletRequest request,
			HttpServletResponse response){
		String idString = request.getParameter("id");
		long id =Long.valueOf(idString);
		AreaGroup areaGroup = areaGroupService.getAreaGroup(id);
		Map<String, AreaGroup> map = new HashMap<String, AreaGroup>();
		map.put("areaGroup", areaGroup);
		String json = JsonUtil.getObjectString(map);
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(json);
		} catch (IOException e) {
			
		}
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		List<Area> provinces = areaService.findProvoce();
		model.addAttribute("provinces", provinces);
		model.addAttribute("areaGroup", new AreaGroup());
		model.addAttribute("action", "create");
		return "areagroup/areaGroupForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid AreaGroup areaGroup, RedirectAttributes redirectAttributes) {
		String[] provinces = areaGroup.getProvinces();
		
		//如果更新之后的省份以前是被其他网点覆盖的，那么需要从其他网点中删除
		if(provinces != null && provinces.length > 0){
			List<AreaGroup> areaGroups = areaGroupService.findAll();
			for(AreaGroup areaGroupTemp: areaGroups){
				if(!(areaGroupTemp.equals(areaGroup))){
					String areas = areaGroupTemp.getAreas();
					for(String province: provinces){
						if(areas.indexOf(province) >= 0){
							String[] areasArray = areas.split(";");
							areas = "";
							for(String area: areasArray){
								if(!(area.equalsIgnoreCase(province))){
									areas += area + ";";
								}
							}
						}
					}
					areaGroupTemp.setAreas(areas);
					areaGroupService.saveAreaGroup(areaGroupTemp);
				}
			}
		}
		
		//更新网点的areas字段（覆盖的省份编码列）
		StringBuffer temp = new StringBuffer();
		if(provinces != null && provinces.length>0)
		{
			for(int i=0; i<provinces.length; i++)
			{
				if("".equals(temp.toString())){
					temp.append(provinces[i]);
				}else{
					temp.append(";"+provinces[i]);
				}
			}
		}
		areaGroup.setAreas(temp.toString());
		areaGroupService.saveAreaGroup(areaGroup);
		
		//对于更新之后的省份，和所覆盖的城市和区县，更新它们在 pms_area 表中的 areagroup_id 字段
		if(provinces != null && provinces.length > 0){
			for(String provinceCode: provinces){
				//根据当前循环的省份编码查询当前循环的省份
				Area province = areaService.findByAreaCode(provinceCode);
				
				//修改省份的服务网点
				province.setAreaGroup(areaGroup);
				areaService.saveArea(province);
				
				//根据上父区域的ID，修改子区域所属的服务网点
				long provinceId = province.getId();
				areaService.updateAreaGroupByParentId(areaGroup, provinceId);
				
				//areaService.updateAreaGroupByGrandParentId(areaGroup, provinceId);
				
				//查询省份下的城市
				List<Area> cities = areaService.getSubAreasById(provinceId);
				//根据城市ID，修改下属的区县的服务网点
				for(Area city: cities){
					areaService.updateAreaGroupByParentId(areaGroup, city.getId());
				}
			}
		}

		redirectAttributes.addFlashAttribute("message", "创建网点成功");
		return "redirect:/areaGroup/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		List<Area> provinces = areaService.findProvoce();
		AreaGroup areaGroup = areaGroupService.getAreaGroup(id);
		String[] currentProvinces = areaGroup.getAreas().split(";");
		model.addAttribute("provinces", provinces);
		model.addAttribute("currentProvinces", currentProvinces);
		model.addAttribute("areaGroup", areaGroupService.getAreaGroup(id));
		model.addAttribute("action", "update");
		return "areagroup/areaGroupForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadAreaGroup") AreaGroup areaGroup, RedirectAttributes redirectAttributes) {
		String[] provinces = areaGroup.getProvinces();
		
		//如果更新之后的省份以前是被其他网点覆盖的，那么需要从其他网点中删除
		if(provinces != null && provinces.length > 0){
			List<AreaGroup> areaGroups = areaGroupService.findAll();
			for(AreaGroup areaGroupTemp: areaGroups){
				if(!(areaGroupTemp.equals(areaGroup))){
					String areas = areaGroupTemp.getAreas();
					for(String province: provinces){
						if(areas.indexOf(province) >= 0){
							String[] areasArray = areas.split(";");
							areas = "";
							for(String area: areasArray){
								if(!(area.equalsIgnoreCase(province))){
									areas += area + ";";
								}
							}
						}
					}
					areaGroupTemp.setAreas(areas);
					areaGroupService.saveAreaGroup(areaGroupTemp);
				}
			}
		}
		
		//更新网点的areas字段（覆盖的省份编码列）
		StringBuffer temp = new StringBuffer();
		if(provinces != null && provinces.length>0)
		{
			for(int i=0; i<provinces.length; i++)
			{
				if("".equals(temp.toString())){
					temp.append(provinces[i]);
				}else{
					temp.append(";"+provinces[i]);
				}
			}
		}
		areaGroup.setAreas(temp.toString());
		
		areaService.updateAreaGroup(null, areaGroup.getId());
		
		//对于更新之后的省份，和所覆盖的城市和区县，更新它们在 pms_area 表中的 areagroup_id 字段
		if(provinces != null && provinces.length > 0){
			for(String provinceCode: provinces){
				//根据当前循环的省份编码查询当前循环的省份
				Area province = areaService.findByAreaCode(provinceCode);
				
				//修改省份的服务网点
				province.setAreaGroup(areaGroup);
				areaService.saveArea(province);
				
				//根据上父区域的ID，修改子区域所属的服务网点
				long provinceId = province.getId();
				areaService.updateAreaGroupByParentId(areaGroup, provinceId);
				
				//areaService.updateAreaGroupByGrandParentId(areaGroup, provinceId);
				
				//查询省份下的城市
				List<Area> cities = areaService.getSubAreasById(provinceId);
				//根据城市ID，修改下属的区县的服务网点
				for(Area city: cities){
					areaService.updateAreaGroupByParentId(areaGroup, city.getId());
				}
			}
		}
		
		areaGroupService.saveAreaGroup(areaGroup);
		redirectAttributes.addFlashAttribute("message", "更新网点成功");
		return "redirect:/areaGroup/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadAreaGroup")
	public AreaGroup getAreaGroup(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return areaGroupService.getAreaGroup(id);
		}
		return null;
	}

	@Autowired
	private AccountService accountService;
	@Autowired
	private CustomersService customersService;
	
	 /**
     * 导向仓库管理页面
     * 废弃原有的方法，利用分页方式查询 libin
     * @param model
     * @param request
     * @return
     */
	@Deprecated
    @RequestMapping(value = "v2_toAreagroupMgrPageBak")
    public String toAreagroupMgrPageBak(Model model, ServletRequest request) {
        try {
            
            //查找商户组
            ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
            User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
            Customers customer=null;
            List<Customers> customerList=null;
            if(user.getUserType().equals("paiu")){ //派友用户
                customerList=this.customersService.findAll();
            }else if(user.getUserType().equals("customer")){ //商家用户
                customerList=new ArrayList<Customers>();
                String customerCode=curUser.customerCode;
                customer=this.customersService.findByCustomerCode(customerCode);
                customerList.add(customer);
            }
            model.addAttribute("customerList",customerList);
            
            List<AreaGroup> groupList=null;
            
            if(user.getUserType().equals("customer")){
                  groupList = this.areaGroupService.loadByCustomerCode(customer.getCustomerCode());
            }else if(user.getUserType().equals("paiu")){
              groupList = this.areaGroupService.findAll();
            }
            
            List<SubWarehouseRel> relList = subWarehouseRelService.findAll();
            for(AreaGroup group:groupList) {
                group.setIsSubWarehouse("N");
                for(SubWarehouseRel rel:relList) {
                    if(group.getGroupCode().equals(rel.getSubWarehouseCode())){
                        group.setIsSubWarehouse("Y");
                        break;
                    }
                }
            }
            
            model.addAttribute("groupList",groupList);
        } catch (Exception e) {
            
        }
        return "areagroup/areagroupMgr";
    }
	
	/**
	 * 导向仓库管理页面
	 * 
	 * @param 
	 * @return 
	 * @throws 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 0.0.16
	 */
	@RequestMapping(value = "v2_toAreagroupMgrPage")
	public String toAreagroupMgrPage(Model model) {
	    
		fillSelectValue(model,null);
		return "areagroup/areagroupMgr";
	}
	
	/**
	 * 分页查询仓库
	 * 
	 * @param 页面的参数命名规则  以 EQ, LIKE, GT, LT, GTE, LTE 开头 + ‘_’ + 列名 
	 * @return 查询结果，分页集合
	 * @throws 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
    @RequestMapping(value = "areagroupPage")
    public void areagroupPage(@RequestBody JSONParam[] paramJson, HttpServletResponse response) {
        try {
            QueryParamHolder paramHolder = collectParamNew(paramJson);
            Page<AreaGroup> page = areaGroupService.pageAreaGroups(paramHolder);
            
            List<SubWarehouseRel> relList = subWarehouseRelService.findAll();
            for (AreaGroup group : page) {
                group.setIsSubWarehouse("N");
                for (SubWarehouseRel rel : relList) {
                    if (group.getGroupCode().equals(rel.getSubWarehouseCode())) {
                        group.setIsSubWarehouse("Y");
                        break;
                    }
                }
            }
            
            response.getWriter().print(bulidJSON(page));
        } catch (Exception e) {
            log.error("查询异常："+e);
        }
    }
	
	/**
	 * 查询订单信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_queryAreagroup")
	public String queryAreagroup(Model model, ServletRequest request) {
		try {
			
			//查找商户组
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
			List<Customers> customerList=null;
			if(user.getUserType().equals("paiu")){ //派友用户
			    customerList=this.customersService.findAll();
			}else if(user.getUserType().equals("customer")){ //商家用户
				customerList=new ArrayList<Customers>();
				String customerCode=curUser.customerCode;
			    Customers customer=this.customersService.findByCustomerCode(customerCode);
				customerList.add(customer);
			}
			model.addAttribute("customerList",customerList);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String customerCode=(String)param.get("customerCode");
			List<AreaGroup> groupList=null;
			if(StringUtils.isNotBlank(customerCode)){
				groupList = this.areaGroupService.loadByCustomerCode(customerCode);
			}else{
				if(user.getUserType().equals("customer")){
				  groupList = this.areaGroupService.loadByCustomerCode(customerCode);
				}else if(user.getUserType().equals("paiu")){
				  groupList = this.areaGroupService.findAll();
				}
			}
			
			List<SubWarehouseRel> relList = subWarehouseRelService.findAll();
			for(AreaGroup group:groupList) {
				group.setIsSubWarehouse("N");
				for(SubWarehouseRel rel:relList) {
					if(group.getGroupCode().equals(rel.getSubWarehouseCode())){
						group.setIsSubWarehouse("Y");
						break;
					}
				}
			}
			
			model.addAttribute("groupList", groupList);
			model.addAttribute("param", Servlets.encodeParameterStringWithPrefix(param, "_"));
			  
		} catch (Exception e) {
			
		}
		
		return "areagroup/areagroupMgr";
	}
	
	/**
	 * 根据商家编码获取网点信息
	 * @param customerCode
	 * @param response
	 */
	@RequestMapping(value="ajaxAreaGroup")
	public void ajaxAreaGroup(@RequestParam(value="customerCode") String customerCode,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		Customers customers=null;
		ShiroUser user=getShiroUser();
		List<AreaGroup> areagroupList=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+customerCode);
			customers=customersService.findByCustomerCode(customerCode);

			if(null==customers){
				json.put("status", "-1");
				json.put("content", "该客户编码不存在");
				out.print(json.toString());
				return;
			}
			
			areagroupList=this.areaGroupService.loadAreaGroupByAuthority(user, customerCode);
			
			json.put("content", areagroupList);
			json.put("status", "1");
			out.print(json.toString());
			log.debug("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value="ajaxHomeAreaGroup")
	public void ajaxHomeAreaGroup(@RequestParam(value="customerCode") String customerCode,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		Customers customers=null;
		List<AreaGroup> areagroupList=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+customerCode);
			customers=customersService.findByCustomerCode(customerCode);

			if(null==customers){
				json.put("status", "-1");
				json.put("content", "该客户编码不存在");
				out.print(json.toString());
				return;
			}
			
			areagroupList=this.areaGroupService.loadAreaGroupByAuthority(customerCode);
			
			json.put("content", areagroupList);
			json.put("status", "1");
			out.print(json.toString());
			log.debug("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value="ajaxUserAreaGroup")
	public void ajaxUserAreaGroup(@RequestParam(value="customerCode") String customerCode,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		Customers customers=null;
		List<AreaGroup> areagroupList=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+customerCode);
			customers=customersService.findByCustomerCode(customerCode);

			if(null==customers){
				json.put("status", "-1");
				json.put("content", "该客户编码不存在");
				out.print(json.toString());
				return;
			}
			
			areagroupList=this.areaGroupService.loadByCustomerCode(customerCode);
			
			json.put("content", areagroupList);
			json.put("status", "1");
			out.print(json.toString());
			log.debug("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
//by libin 2016/08/04	
//	private ShiroUser getShiroUser() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		return user;
//	}
	@Autowired
	private SubWarehouseRelService subWarehouseRelService;
	
	@RequestMapping(value="v2_querySubWarehouse")
	public void querySubWarehouse(@RequestParam(value="mainWarehouseCode") String mainWarehouseCode,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		List<AreaGroup>  allAreaGroup=null;
		List<SubWarehouseRel>  subAssign=null;
		
		List<SubWarehouseRel> allAssign = null;
		List<AreaGroup> delList = new ArrayList<AreaGroup>();
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+mainWarehouseCode);

			allAreaGroup = areaGroupService.findAll();
			allAssign = subWarehouseRelService.findAll();
			for(AreaGroup areaGroup:allAreaGroup) {
				//去掉自己
				if(areaGroup.getGroupCode().equals(mainWarehouseCode)){
					delList.add(areaGroup);
					continue;
				}
				//去掉非派友仓库
				if(!"paiu".equals(areaGroup.getWarehouseType())) {
					delList.add(areaGroup);
					continue;
				}
				//去掉已经有主仓或者已经是主仓的仓库
				for(SubWarehouseRel rel:allAssign){
					if(areaGroup.getGroupCode().equals(rel.getSubWarehouseCode())||
							areaGroup.getGroupCode().equals(rel.getMainWarehouseCode())){
						delList.add(areaGroup);
						break;
					}
				}
			}
			
			subAssign = subWarehouseRelService.findByMainWarehouseCode(mainWarehouseCode);
			for(SubWarehouseRel rel:subAssign){
				for(AreaGroup areaGroup:allAreaGroup){
					if(areaGroup.getGroupCode()==null){
						continue;
					}
					if(areaGroup.getGroupCode().equals(rel.getSubWarehouseCode())){
						rel.setSubWarehouseName(areaGroup.getGroupName());
					}
					if(rel.getMainWarehouseCode().equals(areaGroup.getGroupCode())){
						rel.setMainWarehouseName(areaGroup.getGroupName());
					}
				}
			}
			//删除不符合条件的仓库
			allAreaGroup.removeAll(delList);
			json.put("allAreaGroup", allAreaGroup);
			json.put("subAssign", subAssign);
			json.put("status", "success");
			out.print(json.toString());
			log.debug("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "fail");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
		
	}
	
	@RequestMapping(value="v2_ajaxAssignSubWarehouse")
	public void ajaxAssignSubWarehouse(@RequestParam(value="mainWarehouseCode") String mainWarehouseCode,
			@RequestParam(value="subWarehouseInofStr") String subWarehouseInofStr,
			HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+mainWarehouseCode);
			String[] subWarehouseInfos = subWarehouseInofStr.split(",");
			
			subWarehouseRelService.assignSubWarehouse(mainWarehouseCode, subWarehouseInfos);

			json.put("status", "success");
			out.print(json.toString());
			log.debug("分配主仓编码:"+json.toString());
		} catch (Exception e) {
			json.put("status", "fail");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
		
	}
	
}
